<?php

/**
 * 73yc 订单API接口管理
 * ============================================================================
 * 版权所有 2005-2010 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: yehuaixiao $
 * $Id: order.php 17219 2011-01-27 10:49:19Z yehuaixiao $
 */

define('IN_ECS', true);

require('includes/init.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . 'includes/lib_goods.php');
require(ROOT_PATH . 'includes/cls_json.php');
include_once(ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/admin/order.php');
if($_REQUEST['name']!='21232f297a57a5a743894a0e4a801fc3' || $_REQUEST['pass']!='0192023a7bbd73250516f069df18b500' || $_SERVER['REMOTE_ADDR'] != '42.96.149.21'){
    exit;
}

/*------------------------------------------------------ */
//-- 订单列表
/*------------------------------------------------------ */

//订单处理
if ($_REQUEST['act'] == 'operate')
{

    $order_id=isset($_REQUEST['order_id'])?intval($_REQUEST['order_id']):'';
    $order[0] = order_info($order_id);
    if($order[0]['order_sn'] == $order[0]['join_id']){
        $order = join_info($order_id);
    }

    $action_note    = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
    $username = isset($_REQUEST['username']) ? trim($_REQUEST['username']) : '';
    if(!$username) exit;
    /* 确认 */
    if (isset($_REQUEST['confirm']))
    {
        foreach ($order as $key => $value) {
            /* 标记订单为已确认 */
            update_order($value['order_id'], array('order_status' => OS_CONFIRMED,'confirm_time' => gmtime()));

            /* 记录log */
            order_action($value['order_sn'], OS_CONFIRMED, SS_UNSHIPPED, PS_UNPAYED, $action_note, $username);
        }
    }
    /* 未发货 */
    elseif (isset($_REQUEST['unship']))
    {
        foreach ($order as $key => $value) {
            update_order($value['order_id'], array('shipping_status' => SS_UNSHIPPED, 'shipping_time' => 0, 'invoice_no' => '', 'order_status' => OS_CONFIRMED));
            order_action($value['order_sn'], $value['order_status'], SS_UNSHIPPED, $value['pay_status'], $action_note, $username);
        }
    }
    /* 收货确认 */
    elseif (isset($_REQUEST['receive']))
    {
        $arr = array('shipping_status' => SS_RECEIVED);
        foreach ($order as $key => $value) {
            update_order($value['order_id'], array('shipping_status' => SS_RECEIVED, 'order_status' => 5, 'pay_status' => PS_PAYED, 'pay_time' => time()));
            order_action($value['order_sn'], $value['order_status'], SS_RECEIVED, PS_PAYED, $action_note, $username);
        }
            /* 取得用户信息 */
            $user = user_info($order['user_id']);
            if($order[0]['order_sn']==$order[0]['join_id']){
                $integral = integral_to_give_join($order);
            }else{
                $integral = integral_to_give($order[0]);
            }
            log_account_change($order[0]['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf($_LANG['order_gift_integral'], $order[0]['order_sn']));
            send_order_bonus($order[0]['order_id']);
    }
    /* 订单取消 */
    elseif (isset($_REQUEST['cancel']))
    {
        $area_id=is_buy($order[0]);

        foreach ($order as $key => $value) {
           //获取订单商品
             $goods_list=order_goods($value['order_id']);
             //增加库存
             foreach ($goods_list as $key => $value) {
                    $sql = "SELECT goods_number FROM " . $ecs->table('goods_price') . " WHERE goods_id=" . $value['goods_id'];
                    $number=$db->getOne($sql);
                    $number=intval($number)+$value['goods_number'];
                    $sql = "UPDATE " .$GLOBALS['ecs']->table('goods_price').
                                        " SET goods_number = '$number' WHERE  goods_id=" . $value['goods_id']." AND area_id=".$area_id;
                    $db->getRow($sql);
             }
        }

        $arr = array(
            'order_status'  => OS_CANCELED,
            'to_buyer'      => $action_note,
            'shipping_status'=> SS_UNSHIPPED,
            'pay_status'    => PS_UNPAYED,
            'shipping_time' => 0,
            'pay_time'      => 0,
            'money_paid'    => 0,
            'confirm_time'  => 0,
            'order_amount'  => $order[0]['money_paid']
        );

        foreach ($order as $key => $value) {
            update_order($value['order_id'], $arr);
            order_action($value['order_sn'], OS_CANCELED, SS_UNSHIPPED, PS_UNPAYED, $action_note, $username);
        }




    }
    /* 退货 */
    elseif (isset($_REQUEST['return']))
    {

        $arr = array('order_status'     => OS_RETURNED,
                     'pay_status'       => PS_UNPAYED,
                     'shipping_status'  => SS_UNSHIPPED,
                     'money_paid'       => 0,
                     'invoice_no'       => '',
                     'order_amount'     => $order[0]['money_paid']);
        foreach ($order as $key => $value) {
            update_order($value['order_id'], $arr);
            order_action($value['order_sn'], OS_RETURNED, SS_UNSHIPPED, PS_UNPAYED, $action_note, $username);
        }

    }
    /* 去发货 */
    elseif (isset($_REQUEST['to_delivery']))
    {

        $arr['shipping_status']     = SS_SHIPPED;
        $arr['shipping_time']       = gmtime(); // 发货时间
        $arr['invoice_no'] = intval($_REQUEST['invoice_no']);
        foreach ($order as $key => $value) {
            update_order($value['order_id'], $arr);
            /* 发货单发货记录log */
            order_action($value['order_sn'], OS_CONFIRMED, $arr['shipping_status'], $value['pay_status'], $action_note, $username);
        }
        /* 发送邮件 */
        $cfg = $_CFG['send_ship_email'];
        if ($cfg == '1')
        {
            $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id='" . $order[0]['user_id'] . "'";
            $row = $db->getRow($sql);
            $email=$order[0]['email']?$order[0]['email']:$row['email'];
            $order[0]['invoice_no'] = $action_note;
            $tpl = get_mail_template('deliver_notice');
            $smarty->assign('order', $order[0]);
            $smarty->assign('send_time', local_date($_CFG['time_format']));
            $smarty->assign('shop_name', $_CFG['shop_name']);
            $smarty->assign('send_date', local_date($_CFG['date_format']));
            $smarty->assign('sent_date', local_date($_CFG['date_format']));
            $smarty->assign('confirm_url', $ecs->url() . 'user.php?act=order_list');
            $smarty->assign('send_msg_url',$ecs->url() . 'user.php');
            $content = $smarty->fetch('str:' . $tpl['template_content']);
            if (!send_mail($order[0]['consignee'], $email, $tpl['template_subject'], $content, $tpl['is_html']))
            {
                $msg = $_LANG['send_mail_fail'];
            }
        }
    }
}

/*------------------------------------------------------ */
//-- 订单详细
/*------------------------------------------------------ */

elseif($_REQUEST['act'] == 'info')
{
    /* 根据订单id或订单号查询订单信息 */
    if (isset($_REQUEST['order_id']))
    {
        $order_id = intval($_REQUEST['order_id']);
        $order[0] = order_info($order_id);
        if($order[0]['order_sn'] == $order[0]['join_id']){
            $order = join_info($order_id);
        }
    }
    elseif(isset($_REQUEST['order_sn'])){
        $order[0] = order_info('',intval($_REQUEST['order_sn']));
        if($order[0]['order_sn'] == $order[0]['join_id']){
            $order = join_info($order[0]['order_id']);
        }
    }
    else
    {
        /* 如果参数不存在，退出 */
        die('invalid parameter');
    }
    $goods_lists = array();
    foreach($order AS $key=>$value){
        /* 取得订单商品及货品 */
        $goods_list = array();
        $goods_attr = array();
        $sql = "SELECT o.*, o.goods_attr, o.compose_note,IFNULL(b.brand_name, '') AS brand_name, o.goods_sku,o.goods_attr_sku
                FROM " . $ecs->table('order_goods') . " AS o
                    LEFT JOIN " . $ecs->table('goods') . " AS g
                        ON o.goods_id = g.goods_id
                    LEFT JOIN " . $ecs->table('brand') . " AS b
                        ON g.brand_id = b.brand_id
                WHERE o.order_id = '$value[order_id]'";
        $res = $db->query($sql);
        while ($row = $db->fetchRow($res))
        {

            $row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
            $row['formated_goods_price']    = price_format($row['goods_price']);

            $goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

            $row['order_sn'] = $order[$key]['order_sn'];
            $row['consignee'] = $order[$key]['consignee'];
            $goods_list[] = $row;
        }
        $goods_lists[$key] = $goods_list;
        $goods_attrs[$key] = $goods_attr;
    }
    
    $attr = array();
    $arr  = array();
    foreach ($goods_attrs as $k => $v) {
        foreach ($v AS $index => $array_val)
        {
            foreach ($array_val AS $value)
            {
                $arr = explode(':', $value);//以 : 号将属性拆开
                $attr[$k][$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
            }
        }
    }
    /* 打印快递单 */
    if ($_GET['shipping_print']){
        //发货地址所在地
        $region_array = array();
        $region_id = !empty($_CFG['shop_country']) ? $_CFG['shop_country'] . ',' : '';
        $region_id .= !empty($_CFG['shop_province']) ? $_CFG['shop_province'] . ',' : '';
        $region_id .= !empty($_CFG['shop_city']) ? $_CFG['shop_city'] . ',' : '';
        $region_id .= $order[0]['country'].','.$order[0]['province'].','.$order[0]['city'].','.$order[0]['district'].',';
        $region_id = substr($region_id, 0, -1);
        $region = $db->getAll("SELECT region_id, region_name FROM " . $ecs->table("region") . " WHERE region_id IN ($region_id)");
        if (!empty($region))
        {
            foreach($region as $region_data)
            {
                $region_array[$region_data['region_id']] = $region_data['region_name'];
            }
        }
        $shipping = $db->getRow("SELECT * FROM " . $ecs->table("shipping") . " WHERE shipping_id = " . $order[0]['shipping_id']);

        if($order[0]['pay_id']!=3){
            $shipping['config_lable'] = "t_shop_province,网店-省份,63,21,131,161,b_shop_province||,||t_customer_province,收件人-省份,63,21,498,158,b_customer_province||,||t_shop_address,网店-地址,184,21,130,207,b_shop_address||,||t_shop_name,网店-名称,180,21,134,87,b_shop_name||,||t_shop_tel,网店-联系电话,133,21,179,236,b_shop_tel||,||t_customer_tel,收件人-电话,135,21,648,231,b_customer_tel||,||t_customer_mobel,收件人-手机,134,21,600,231,b_customer_mobel||,||t_customer_name,收件人-姓名,91,21,506,92,b_customer_name||,||t_customer_address,收件人-详细地址,318,21,461,195,b_customer_address||,||t_months,月-当日日期,39,21,200,385,b_months||,||t_day,日-当日日期,28,21,238,385,b_day||,||t_shop_city,网店-城市,65,21,215,161,b_shop_city||,||t_shop_district,网店-区/县,68,21,304,158,b_shop_district||,||t_customer_city,收件人-城市,63,21,590,157,b_customer_city||,||t_customer_district,收件人-区/县,70,21,672,157,b_customer_district||,||t_shipping_fee,邮费已收,134,21,690,310,t_shipping_fee||,||t_year,年-当日日期,47,21,145,385,b_year||,||";
        }else{
            $shipping['config_lable'] = "t_shop_province,网店-省份,63,21,129,192,b_shop_province||,||t_customer_province,收件人-省份,63,21,422,188,b_customer_province||,||t_shop_address,网店-地址,184,21,128,231,b_shop_address||,||t_shop_name,网店-名称,180,21,183,141,b_shop_name||,||t_shop_tel,网店-联系电话,133,21,248,110,b_shop_tel||,||t_customer_tel,收件人-电话,135,21,573,135,b_customer_tel||,||t_customer_mobel,收件人-手机,134,21,573,103,b_customer_mobel||,||t_customer_name,收件人-姓名,91,21,423,112,b_customer_name||,||t_customer_address,收件人-详细地址,318,21,394,220,b_customer_address||,||t_months,月-当日日期,27,21,359,316,b_months||,||t_day,日-当日日期,28,21,391,316,b_day||,||t_shop_city,网店-城市,65,21,197,192,b_shop_city||,||t_shop_district,网店-区/县,68,21,273,191,b_shop_district||,||t_customer_city,收件人-城市,63,21,500,186,b_customer_city||,||t_customer_district,收件人-区/县,96,21,573,186,b_customer_district||,||t_pigeon,√-对号,21,21,520,383,b_pigeon||,||t_total_fee,小写金额,99,21,732,349,t_total_fee||,||t_shipping_fee,邮费已收,99,21,728,384,t_shipping_fee||,||t_year,年-当日日期,47,21,308,316,b_year||,||";
        }

        //打印单模式
        if ($shipping['print_model'] == 2)
        {
            /* 可视化 */
            /* 快递单 */
            $shipping['print_bg'] = empty($shipping['print_bg']) ? '' : $shipping['print_bg'];

            /* 取快递单背景宽高 */
            if (!empty($shipping['print_bg']))
            {
                $_size = @getimagesize($shipping['print_bg']);

                if ($_size != false)
                {
                    $shipping['print_bg_size'] = array('width' => $_size[0], 'height' => $_size[1]);
                }
            }

            if (empty($shipping['print_bg_size']))
            {
                $shipping['print_bg_size'] = array('width' => '800', 'height' => '467');
            }

            /* 标签信息 */
            $lable_box = array();
            $lable_box['t_shop_country'] = $region_array[$_CFG['shop_country']]; //网店-国家
            $lable_box['t_shop_city'] = $region_array[$_CFG['shop_city']]; //网店-城市
            $lable_box['t_shop_province'] = $region_array[$_CFG['shop_province']]; //网店-省份
            $lable_box['t_shop_name'] = $_CFG['shop_name']; //网店-名称
            $lable_box['t_shop_district'] = ''; //网店-区/县
            $lable_box['t_shop_tel'] = $_CFG['service_phone']; //网店-联系电话
            $lable_box['t_shop_address'] = $_CFG['shop_address']; //网店-地址
            $lable_box['t_customer_country'] = $region_array[$order[0]['country']]; //收件人-国家
            $lable_box['t_customer_province'] = $region_array[$order[0]['province']]; //收件人-省份
            $lable_box['t_customer_city'] = $region_array[$order[0]['city']]; //收件人-城市
            $lable_box['t_customer_district'] = $region_array[$order[0]['district']]; //收件人-区/县
            $lable_box['t_customer_tel'] = $order[0]['tel']; //收件人-电话
            $lable_box['t_customer_mobel'] = $order[0]['mobile']; //收件人-手机
            $lable_box['t_customer_post'] = $order[0]['zipcode']; //收件人-邮编
            $lable_box['t_customer_address'] = $order[0]['address']; //收件人-详细地址
            $lable_box['t_customer_name'] = $order[0]['consignee']; //收件人-姓名
            $lable_box['t_shipping_fee'] = '邮费已收';

            $gmtime_utc_temp = gmtime(); //获取 UTC 时间戳
            $lable_box['t_year'] = date('Y', $gmtime_utc_temp); //年-当日日期
            $lable_box['t_months'] = date('m', $gmtime_utc_temp); //月-当日日期
            $lable_box['t_day'] = date('d', $gmtime_utc_temp); //日-当日日期

            $lable_box['t_order_no'] = $order[0]['order_sn']; //订单号-订单
            $lable_box['t_order_postscript'] = $order[0]['postscript']; //备注-订单
            $lable_box['t_order_best_time'] = $order[0]['best_time']; //送货时间-订单
            if($order[0]['pay_id']==3){
                $lable_box['t_pigeon'] = '√'; //√-对号
                $lable_box['t_total_fee_cny'] = cny(round($order[0]['order_amounts'],1)); //代收费用
                $lable_box['t_total_fee'] = $order[0]['order_amounts']; //代收费用
            }
            $lable_box['t_custom_content'] = ''; //自定义内容

            //标签替换
            $temp_config_lable = explode('||,||', $shipping['config_lable']);
            if (!is_array($temp_config_lable))
            {
                $temp_config_lable[] = $shipping['config_lable'];
            }
            foreach ($temp_config_lable as $temp_key => $temp_lable)
            {
                $temp_info = explode(',', $temp_lable);
                if (is_array($temp_info))
                {
                    $temp_info[1] = $lable_box[$temp_info[0]];
                }
                $temp_config_lable[$temp_key] = implode(',', $temp_info);
            }
            $shipping['config_lable'] = implode('||,||',  $temp_config_lable);
        }
    }

    $operable_list = operable_list($order[0]);
    /* 取得订单操作记录 */
    $act_list = array();
    $sql = "SELECT * FROM " . $ecs->table('order_action') . " WHERE order_id = '" . $order[0]['order_id'] . "' ORDER BY log_time DESC,action_id DESC";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {
        $row['order_status']    = $_LANG['os'][$row['order_status']];
        $row['pay_status']      = $_LANG['ps'][$row['pay_status']];
        $row['shipping_status'] = $_LANG['ss'][$row['shipping_status']];
        $row['action_time']     = local_date($_CFG['time_format'], $row['log_time']);
        $act_list[] = $row;
    }
    
    die(json_encode(array('order'=>$order,'goods_lists'=>$goods_lists, 'shipping'=>$shipping, 'operable_list'=>$operable_list, 'act_list'=>$act_list, 'goods_attr'=>$goods_attrs)));
}

/**
 *  获取订单列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function order_list($region=null, $pages_start=0, $size=20, $order_sn=0, $sw='', $sort='', $status='')
{
    if($status != 4){
        $sw .= " AND ((o.pay_id != 3 AND o.pay_status = 2) OR (o.pay_id = 3))";
    }
        $sql='SELECT o.*,u.*,p.order_amount AS order_amounts,(o.goods_amount - o.discount + o.tax + o.insure_fee + o.pay_fee) AS total_fee FROM ' . $GLOBALS['ecs']->table('order_info') . " o ".
            " LEFT JOIN " . $GLOBALS['ecs']->table('users') . " u ON u.user_id = o.user_id " . 
            " LEFT JOIN " . $GLOBALS['ecs']->table('pay_log') . " p ON p.order_id = o.order_id " . 
            " WHERE " . ($region?"(o.province IN ($region) OR o.city IN ($region) OR o.district IN ($region)) AND ":' '). ($order_sn>0?" (order_sn = $order_sn OR invoice_no = $order_sn) AND ":'') . " (o.join_id = 0 OR o.join_id = o.order_sn) $sw $sort LIMIT $pages_start, $size ";
        $arr= $GLOBALS['db']->getAll($sql);
        return $arr;
}


/**
 * 返回某个订单可执行的操作列表，包括权限判断
 * @param   array   $order      订单信息 order_status, shipping_status, pay_status
 * @param   bool    $is_cod     支付方式是否货到付款
 * @return  array   可执行的操作  confirm, pay, unpay, prepare, ship, unship, receive, cancel, invalid, return, drop
 * 格式 array('confirm' => true, 'pay' => true)
 */
function operable_list($order)
{
    /* 取得订单状态、发货状态、付款状态 */
    $os = $order['order_status'];
    $ss = $order['shipping_status'];
    $ps = $order['pay_status'];
    /* 取得订单操作权限 */
        $priv_list  = array('os' => true, 'ss' => true, 'ps' => true, 'edit' => true);

    /* 取得订单支付方式是否货到付款 */
    $payment = payment_info($order['pay_id']);
    $is_cod  = $payment['is_cod'] == 1;

    /* 根据状态返回可执行操作 */
    $list = array();
    if (OS_UNCONFIRMED == $os)
    {
        /* 状态：未确认 => 未付款、未发货 */
        if ($priv_list['os'])
        {
            $list['confirm']    = true; // 确认
            $list['invalid']    = true; // 无效
            $list['cancel']     = true; // 取消
            $list['confirm_join']    = true; // 确认
            $list['invalid_join']    = true; // 无效
            $list['cancel_join']     = true; // 取消
            if ($is_cod)
            {
                /* 货到付款 */
                if ($priv_list['ss'])
                {
                    $list['prepare'] = true; // 配货
                    $list['split'] = true; // 分单
                    $list['prepare_join'] = true; // 配货
                    $list['split_join'] = true; // 分单
                }
            }
            else
            {
                /* 不是货到付款 */
                if ($priv_list['ps'])
                {
                    $list['pay'] = true;  // 付款
                    $list['pay_join'] = true;  // 付款
                }
            }
        }
    }
    elseif (OS_CONFIRMED == $os || OS_SPLITED == $os || OS_SPLITING_PART == $os)
    {
        /* 状态：已确认 */
        if (PS_UNPAYED == $ps)
        {
            /* 状态：已确认、未付款 */
            if (SS_UNSHIPPED == $ss || SS_PREPARING == $ss)
            {
                /* 状态：已确认、未付款、未发货（或配货中） */
                if ($priv_list['os'])
                {
                    $list['cancel'] = true; // 取消
                    $list['cancel_join'] = true; // 取消
                    $list['invalid'] = true; // 无效
                    $list['invalid_join'] = true; // 无效
                }
                if ($is_cod)
                {
                    /* 货到付款 */
                    if ($priv_list['ss'])
                    {
                        if (SS_UNSHIPPED == $ss)
                        {
                            $list['prepare'] = true; // 配货
                            $list['prepare_join'] = true; // 配货
                        }
                        $list['split'] = true; // 分单
                        $list['split_join'] = true; // 分单
                    }
                }
                else
                {
                    /* 不是货到付款 */
                    if ($priv_list['ps'])
                    {
                        $list['pay'] = true; // 付款
                        $list['pay_join'] = true; // 付款
                    }
                }
            }
            /* 状态：已确认、未付款、发货中 */
            elseif (SS_SHIPPED_ING == $ss || SS_SHIPPED_PART == $ss)
            {
                // 部分分单
                if (OS_SPLITING_PART == $os)
                {
                    $list['split'] = true; // 分单
                    $list['split_join'] = true; // 分单
                }
                $list['to_delivery'] = true; // 去发货
                $list['to_delivery_join'] = true; // 去发货
            }
            else
            {
                /* 状态：已确认、未付款、已发货或已收货 => 货到付款 */
                if ($priv_list['ps'])
                {
                    $list['pay'] = true; // 付款
                    $list['pay_join'] = true; // 付款
                }
                if ($priv_list['ss'])
                {
                    if (SS_SHIPPED == $ss)
                    {
                        $list['receive'] = true; // 收货确认
                        $list['receive_join'] = true; // 收货确认
                    }
                    $list['unship'] = true; // 设为未发货
                    $list['unship_join'] = true; // 设为未发货
                    if ($priv_list['os'])
                    {
                        $list['return'] = true; // 退货
                        $list['return_join'] = true; // 退货
                    }
                }
            }
        }
        else
        {
            /* 状态：已确认、已付款和付款中 */
            if (SS_UNSHIPPED == $ss || SS_PREPARING == $ss)
            {
                /* 状态：已确认、已付款和付款中、未发货（配货中） => 不是货到付款 */
                if ($priv_list['ss'])
                {
                    if (SS_UNSHIPPED == $ss)
                    {
                        $list['prepare'] = true; // 配货
                        $list['prepare_join'] = true; // 配货
                    }
                    $list['split'] = true; // 分单
                    $list['split_join'] = true; // 分单
                }
                if ($priv_list['ps'])
                {
                    $list['unpay'] = true; // 设为未付款
                    $list['unpay_join'] = true; // 设为未付款
                    if ($priv_list['os'])
                    {
                        $list['cancel'] = true; // 取消
                        $list['cancel_join'] = true; // 取消
                    }
                }
            }
            /* 状态：已确认、未付款、发货中 */
            elseif (SS_SHIPPED_ING == $ss || SS_SHIPPED_PART == $ss)
            {
                // 部分分单
                if (OS_SPLITING_PART == $os)
                {
                    $list['split'] = true; // 分单
                    $list['split_join'] = true; // 分单
                }
                $list['to_delivery'] = true; // 去发货
                $list['to_delivery_join'] = true; // 去发货
            }
            else
            {
                /* 状态：已确认、已付款和付款中、已发货或已收货 */
                if ($priv_list['ss'])
                {
                    if (SS_SHIPPED == $ss)
                    {
                        $list['receive'] = true; // 收货确认
                        $list['receive_join'] = true; // 收货确认
                    }
                    if (!$is_cod)
                    {
                        $list['unship'] = true; // 设为未发货
                        $list['unship_join'] = true; // 设为未发货
                    }
                }
                if ($priv_list['ps'] && $is_cod)
                {
                    $list['unpay']  = true; // 设为未付款
                    $list['unpay_join']  = true; // 设为未付款
                }
                if ($priv_list['os'] && $priv_list['ss'] && $priv_list['ps'])
                {
                    $list['return'] = true; // 退货（包括退款）
                    $list['return_join'] = true; // 退货（包括退款）
                }
            }
        }
    }
    elseif (OS_CANCELED == $os)
    {
        /* 状态：取消 */
        if ($priv_list['os'])
        {
            $list['confirm'] = true;
            $list['confirm_join'] = true;
        }
        if ($priv_list['edit'])
        {
            $list['remove'] = true;
            $list['remove_join'] = true;
        }
    }
    elseif (OS_INVALID == $os)
    {
        /* 状态：无效 */
        if ($priv_list['os'])
        {
            $list['confirm'] = true;
            $list['confirm_join'] = true;
        }
        if ($priv_list['edit'])
        {
            $list['remove'] = true;
            $list['remove_join'] = true;
        }
    }
    elseif (OS_RETURNED == $os)
    {
        /* 状态：退货 */
        if ($priv_list['os'])
        {
            $list['confirm'] = true;
            $list['confirm_join'] = true;
        }
    }

    /* 修正发货操作 */
    if (!empty($list['split']))
    {
        unset($list['cancel_join']); // 取消
    }

    /* 售后 */
    $list['after_service'] = true;
    $list['after_service_join'] = true;

    return $list;
}




/**
 * 判断订单是否已发货（含部分发货）
 * @param   int     $order_id  订单 id
 * @return  int     1，已发货；0，未发货
 */
function order_deliveryed($order_id)
{
    $return_res = 0;

    if (empty($order_id))
    {
        return $return_res;
    }

    $sql = 'SELECT COUNT(delivery_id)
            FROM ' . $GLOBALS['ecs']->table('delivery_order') . '
            WHERE order_id = \''. $order_id . '\'
            AND status = 0';
    $sum = $GLOBALS['db']->getOne($sql);

    if ($sum)
    {
        $return_res = 1;
    }

    return $return_res;
}

/**
 * 订单中的商品是否已经全部发货
 * @param   int     $order_id  订单 id
 * @return  int     1，全部发货；0，未全部发货
 */
function get_order_finish($order_id)
{
    $return_res = 0;

    if (empty($order_id))
    {
        return $return_res;
    }

    $sql = 'SELECT COUNT(rec_id)
            FROM ' . $GLOBALS['ecs']->table('order_goods') . '
            WHERE order_id = \'' . $order_id . '\'
            AND goods_number > send_number';

    $sum = $GLOBALS['db']->getOne($sql);
    if (empty($sum))
    {
        $return_res = 1;
    }

    return $return_res;
}

/**
 * 判断订单的发货单是否全部发货
 * @param   int     $order_id  订单 id
 * @return  int     1，全部发货；0，未全部发货；-1，部分发货；-2，完全没发货；
 */
function get_all_delivery_finish($order_id)
{
    $return_res = 0;

    if (empty($order_id))
    {
        return $return_res;
    }

    /* 未全部分单 */
    if (!get_order_finish($order_id))
    {
        return $return_res;
    }
    /* 已全部分单 */
    else
    {
        // 是否全部发货
        $sql = "SELECT COUNT(delivery_id)
                FROM " . $GLOBALS['ecs']->table('delivery_order') . "
                WHERE order_id = '$order_id'
                AND status = 2 ";
        $sum = $GLOBALS['db']->getOne($sql);
        // 全部发货
        if (empty($sum))
        {
            $return_res = 1;
        }
        // 未全部发货
        else
        {
            /* 订单全部发货中时：当前发货单总数 */
            $sql = "SELECT COUNT(delivery_id)
            FROM " . $GLOBALS['ecs']->table('delivery_order') . "
            WHERE order_id = '$order_id'
            AND status <> 1 ";
            $_sum = $GLOBALS['db']->getOne($sql);
            if ($_sum == $sum)
            {
                $return_res = -2; // 完全没发货
            }
            else
            {
                $return_res = -1; // 部分发货
            }
        }
    }

    return $return_res;
}


/**
 * 数字转金额大写
 *
 * @access  private
 * @return  Bool
 */
function cny($ns) { 
    static $cnums=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"), 
        $cnyunits=array("元","角","分"), 
        $grees=array("拾","佰","仟","万","拾","佰","仟","亿"); 
    list($ns1,$ns2)=explode(".",$ns,2); 
    $ns2=array_filter(array($ns2[1],$ns2[0])); 
    $ret=array_merge($ns2,array(implode("",_cny_map_unit(str_split($ns1),$grees)),"")); 
    $ret=implode("",array_reverse(_cny_map_unit($ret,$cnyunits))); 
    return str_replace(array_keys($cnums),$cnums,$ret); 
}
function _cny_map_unit($list,$units) { 
    $ul=count($units); 
    $xs=array(); 
    foreach (array_reverse($list) as $x) { 
        $l=count($xs);
        if ($x!="0" || !($l%4)) $n=($x=='0'?'':$x).($units[($l-1)%$ul]); 
        else $n=is_numeric($xs[0][0])?$x:''; 
        array_unshift($xs,$n); 
    }
    return $xs; 
}

?>
